<template>
    <div :class="['login-container', { 'sign-up-mode': !isLogin }]">
        <div class="back-btn" @click="goBack">
            <i class="fas fa-arrow-left"></i>
        </div>
        
        <div class="forms-container">
            <div class="signin-signup">
                <!-- 登录表单 -->
                <form action="#" class="sign-in-form" @submit.prevent="handleLogin" :style="{ zIndex: isLogin ? 2 : 1, opacity: isLogin ? 1 : 0 }">
                    <h2 class="title">登录</h2>
                    <div class="login-type">
                        <span @click="switchLoginType('password')" :class="{ active: loginType === 'password' }">密码登录</span>
                        <span @click="switchLoginType('code')" :class="{ active: loginType === 'code' }">验证码登录</span>
                    </div>
                    
                    <!-- 密码登录 -->
                    <template v-if="loginType === 'password'">
                        <div class="input-field">
                            <i class="iconfont icon-user"></i>
                            <input type="text" v-model="loginForm.account" placeholder="请输入邮箱/手机号" :disabled="loading" />
                        </div>
                        <div class="input-field">
                            <i class="iconfont icon-lock"></i>
                            <input type="password" v-model="loginForm.password" placeholder="请输入密码" :disabled="loading" />
                        </div>
                    </template>
                    
                    <!-- 验证码登录 -->
                    <template v-if="loginType === 'code'">
                        <div class="input-field">
                            <i class="iconfont icon-email"></i>
                            <input type="text" v-model="loginForm.account" placeholder="请输入邮箱地址" :disabled="loading" />
                        </div>
                        <div class="input-field verification-field">
                            <i class="iconfont icon-verification"></i>
                            <input type="text" v-model="loginForm.code" placeholder="请输入验证码" :disabled="loading" />
                            <button type="button" class="code-btn" @click.prevent="handleGetCode" :disabled="countdown > 0 || loading">
                                {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
                            </button>
                        </div>
                    </template>
                    
                    <button type="button" class="btn solid" @click="handleLogin" :disabled="loading">
                        {{ loading ? '登录中...' : '立即登录' }}
                    </button>
                    <div class="loading-spinner" v-if="loading"></div>
                    
                    <!-- 忘记密码链接 -->
                    <div class="forgot-password">
                        <span @click="showResetPasswordModal = true">忘记密码?</span>
                    </div>
                </form>

                <!-- 注册表单 -->
                <form action="#" class="sign-up-form" @submit.prevent="handleRegister" :style="{ zIndex: !isLogin ? 2 : 1, opacity: !isLogin ? 1 : 0 }">
                    <h2 class="title">账号注册</h2>
                    <div class="register-type" :class="{ 'email-active': registerType === 'email', 'account-active': registerType === 'account' }">
                        <span @click="switchRegisterType('email')" :class="{ active: registerType === 'email' }">邮箱验证注册</span>
                        <span @click="switchRegisterType('account')" :class="{ active: registerType === 'account' }">账号密码注册</span>
                    </div>
                    
                    <!-- 邮箱验证码注册 -->
                    <div class="register-form-content email-register" v-if="registerType === 'email'">
                        <div class="input-field">
                            <i class="iconfont icon-email"></i>
                            <input type="text" v-model="registerForm.account" placeholder="请输入邮箱地址" :disabled="loading" />
                        </div>
                        <div class="input-field">
                            <i class="iconfont icon-lock"></i>
                            <input type="password" v-model="registerForm.password" placeholder="密码（6-20位字母、数字或下划线）" :disabled="loading" />
                        </div>
                        <div class="input-field verification-field">
                            <i class="iconfont icon-verification"></i>
                            <input type="text" v-model="registerForm.code" placeholder="请输入验证码" :disabled="loading" />
                            <button type="button" class="code-btn" @click.prevent="sendRegisterCode" :disabled="registerCodeTimer > 0 || loading">
                                {{ registerCodeTimer > 0 ? `${registerCodeTimer}s` : '获取验证码' }}
                            </button>
                        </div>
                    </div>
                    
                    <!-- 账号密码注册 -->
                    <div class="register-form-content account-register" v-if="registerType === 'account'">
                        <div class="input-field-wrapper">
                            <div class="input-field">
                                <i class="iconfont icon-user"></i>
                                <input 
                                    type="text" 
                                    v-model="accountRegisterForm.username" 
                                    placeholder="请输入用户名" 
                                    :disabled="loading"
                                    @input="onUsernameInput" 
                                    @focus="showUsernameSuggestions = true"
                                    @blur="hideUsernameSuggestions" 
                                />
                            </div>
                            <div class="username-suggestions" v-show="showUsernameSuggestions && randomUsernameSuggestions.length > 0">
                                <div class="suggestion-title">推荐用户名：</div>
                                <div 
                                    v-for="(name, index) in randomUsernameSuggestions" 
                                    :key="'username-'+index" 
                                    class="username-suggestion-item"
                                    @mousedown="selectUsername(name)"
                                >
                                    {{ name }}
                                </div>
                            </div>
                        </div>
                        <div class="input-field">
                            <i class="iconfont icon-user"></i>
                            <input type="text" v-model="accountRegisterForm.nickname" placeholder="请输入昵称" :disabled="loading" />
                        </div>
                        <div class="input-field">
                            <i class="iconfont icon-email"></i>
                            <input type="text" v-model="accountRegisterForm.email" placeholder="请输入邮箱地址" :disabled="loading" />
                        </div>
                        <div class="input-field">
                            <i class="iconfont icon-phone"></i>
                            <input type="text" v-model="accountRegisterForm.mobile" placeholder="请输入手机号码" :disabled="loading" />
                        </div>
                        <div class="input-field">
                            <i class="iconfont icon-lock"></i>
                            <input type="password" v-model="accountRegisterForm.password" placeholder="密码（6-20位字母、数字或下划线）" :disabled="loading" />
                        </div>
                    </div>
                    
                    <button type="button" class="btn solid register-btn" @click="handleRegister" :disabled="loading">
                        {{ loading ? '注册中...' : '立即注册' }}
                    </button>
                    <div class="loading-spinner" v-if="loading"></div>
                </form>
            </div>
        </div>

        <!-- 重置密码模态窗口 -->
        <div class="modal-overlay" v-if="showResetPasswordModal" @click="closeResetPasswordModal"></div>
        <div class="modal-container" v-if="showResetPasswordModal">
            <div class="modal-header">
                <h3>重置密码</h3>
                <span class="close-btn" @click="closeResetPasswordModal">&times;</span>
            </div>
            <div class="modal-body">
                <div class="reset-password-step" v-if="resetPasswordStep === 1">
                    <div class="input-field">
                        <i class="iconfont icon-email"></i>
                        <input type="text" v-model="resetPasswordForm.email" placeholder="请输入注册邮箱" :disabled="loading" />
                    </div>
                    <div class="input-field verification-field">
                        <i class="iconfont icon-verification"></i>
                        <input type="text" v-model="resetPasswordForm.code" placeholder="请输入验证码" :disabled="loading" />
                        <button type="button" class="code-btn" @click.prevent="sendPasswordResetCode" :disabled="resetPasswordCodeTimer > 0 || loading">
                            {{ resetPasswordCodeTimer > 0 ? `${resetPasswordCodeTimer}s` : '获取验证码' }}
                        </button>
                    </div>
                    <button type="button" class="btn solid" @click="verifyResetCode" :disabled="loading">
                        {{ loading ? '验证中...' : '下一步' }}
                    </button>
                </div>
                
                <div class="reset-password-step" v-if="resetPasswordStep === 2">
                    <div class="input-field">
                        <i class="iconfont icon-lock"></i>
                        <input type="password" v-model="resetPasswordForm.newPassword" placeholder="请输入新密码" :disabled="loading" />
                    </div>
                    <div class="input-field">
                        <i class="iconfont icon-lock"></i>
                        <input type="password" v-model="resetPasswordForm.confirmPassword" placeholder="请确认新密码" :disabled="loading" />
                    </div>
                    <button type="button" class="btn solid" @click="handleResetPassword" :disabled="loading">
                        {{ loading ? '重置中...' : '重置密码' }}
                    </button>
                </div>
                
                <div class="reset-password-step" v-if="resetPasswordStep === 3">
                    <div class="success-message">
                        <i class="iconfont icon-success"></i>
                        <p>密码重置成功！</p>
                    </div>
                    <button type="button" class="btn solid" @click="closeResetPasswordModal">
                        返回登录
                    </button>
                </div>
            </div>
        </div>

        <div class="panels-container">
            <div class="panel left-panel">
                <div class="content">
                    <h3>加入我们</h3>
                    <p>加入我们，成为本站的一份子。</p>
                    <button class="btn transparent" @click="switchToRegister">
                        去注册
                    </button>
                </div>
                <img src="/static/images/signin.svg" class="image" alt="" />
            </div>
            <div class="panel right-panel">
                <div class="content">
                    <h3>已有帐号？</h3>
                    <p>立即登录已有帐号，享受独家权益。</p>
                    <button class="btn transparent" @click="switchToLogin">
                        去登录
                    </button>
                </div>
                <img src="/static/images/signup.svg" class="image" alt="" />
            </div>
        </div>
        
        <!-- 移动端专用切换按钮 -->
        <div class="mobile-toggle" v-if="isMobileView" @click="toggleForm">
            {{ isLogin ? '没有账号？去注册' : '已有账号？去登录' }}
        </div>
    </div>
</template>

<script>
import { login, registerByCode, registerByAccount, getLoginCode, getRegisterCode, getResetPasswordCode, resetPassword } from '@/api/auth';
import request from '@/utils/request';

export default {
    data() {
        // 生成随机数字或字母组合
        const generateRandomSuffix = () => {
            const chars = '0123456789abcdefghijklmnopqrstuvwxyz';
            let result = '';
            for (let i = 0; i < 3; i++) {
                result += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            return result;
        };
        
        // 生成带随机后缀的用户名和昵称
        const generateRandomUsernames = (baseNames) => {
            return baseNames.map(name => `${name}${generateRandomSuffix()}`);
        };
        
        const usernameBase = ['天涯过客', '云中漫步', '智慧星人', '快乐旅行家', '创新达人', 
                            '春风十里', '陽光燦爛', '文学少年', '科技先锋', '海洋之心'];
        
        const nicknameBase = ['小智', '阳光boy', '快乐精灵', '蓝色梦想', '绿野仙踪',
                           '星辰大海', '悠闲客', '知行合一', '创想家', '未来领航员'];
        
        return {
            isLogin: true,
            loginType: 'password',
            registerType: 'account', // 默认为账号密码注册
            isMobileView: false, // 添加移动设备视图检测
            codeTimer: 0,
            registerCodeTimer: 0,
            resetPasswordCodeTimer: 0,
            loading: false,
            showResetPasswordModal: false,
            resetPasswordStep: 1,
            loginForm: {
                account: '',
                loginType: 'password',
                password: '',
                code: ''
            },
            registerForm: {
                account: '',
                password: '',
                code: ''
            },
            resetPasswordForm: {
                email: '',
                code: '',
                newPassword: '',
                confirmPassword: ''
            },
            accountRegisterForm: {
                username: '',
                nickname: '',
                mobile: '',
                email: '',
                password: ''
            },
            showUsernameSuggestions: false,
            showNicknameSuggestions: false,
            usernameSuggestions: generateRandomUsernames(usernameBase),
            nicknameSuggestions: generateRandomUsernames(nicknameBase),
            countdown: 0,
            timer: null,
            registerTimer: null,
            resetPasswordTimer: null,
            randomUsernameSuggestions: [],
            adjectives: ['快乐', '智慧', '勇敢', '飞翔', '奔跑', '微笑', '雄鹰', '闪耀', '梦想', '勤奋', '活力', '文艺', '优雅', '创意', '欢乐'],
            nouns: ['企鹅', '猫咪', '旅人', '骑士', '精灵', '勇士', '海豚', '天使', '花朵', '星星', '宇航员', '舞者', '歌手', '画家', '探险家'],
        }
    },
    methods: {
        goBack() {
            uni.reLaunch({
                url: '/pages/index/index'
            });
        },
        switchLoginType(type) {
            if (this.loading) return;
            this.loginType = type;
            this.loginForm.loginType = type;
            this.loginForm.password = '';
            this.loginForm.code = '';
        },
        switchRegisterType(type) {
            if (this.loading) return;
            this.registerType = type;
        },
        validateLoginForm() {
            if (!this.loginForm.account) {
                uni.showToast({
                    title: '请输入账号',
                    icon: 'none'
                });
                return false;
            }
            if (this.loginType === 'password' && !this.loginForm.password) {
                uni.showToast({
                    title: '请输入密码',
                    icon: 'none'
                });
                return false;
            }
            if (this.loginType === 'code') {
                if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.loginForm.account)) {
                    uni.showToast({
                        title: '请输入正确的邮箱地址',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.loginForm.code) {
                    uni.showToast({
                        title: '请输入验证码',
                        icon: 'none'
                    });
                    return false;
                }
            }
            return true;
        },
        validateRegisterForm() {
            if (this.registerType === 'email') {
                // 邮箱验证码注册验证
                if (!this.registerForm.account) {
                    uni.showToast({
                        title: '请输入邮箱',
                        icon: 'none'
                    });
                    return false;
                }
                if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.registerForm.account)) {
                    uni.showToast({
                        title: '请输入正确的邮箱地址',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.registerForm.password) {
                    uni.showToast({
                        title: '请输入密码',
                        icon: 'none'
                    });
                    return false;
                }
                if (!/^[a-zA-Z0-9_]{6,20}$/.test(this.registerForm.password)) {
                    uni.showToast({
                        title: '密码必须是6-20位字母、数字或下划线',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.registerForm.code) {
                    uni.showToast({
                        title: '请输入验证码',
                        icon: 'none'
                    });
                    return false;
                }
            } else {
                // 账号密码注册验证
                if (!this.accountRegisterForm.username) {
                    uni.showToast({
                        title: '请输入用户名',
                        icon: 'none'
                    });
                    return false;
                }
                if (!/^[\u4e00-\u9fa5a-zA-Z0-9_]{2,20}$/.test(this.accountRegisterForm.username)) {
                    uni.showToast({
                        title: '用户名必须是2-20位中文、字母、数字或下划线',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.accountRegisterForm.nickname) {
                    uni.showToast({
                        title: '请输入昵称',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.accountRegisterForm.email) {
                    uni.showToast({
                        title: '请输入邮箱',
                        icon: 'none'
                    });
                    return false;
                }
                if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.accountRegisterForm.email)) {
                    uni.showToast({
                        title: '请输入正确的邮箱地址',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.accountRegisterForm.mobile) {
                    uni.showToast({
                        title: '请输入手机号',
                        icon: 'none'
                    });
                    return false;
                }
                if (!/^1[3-9]\d{9}$/.test(this.accountRegisterForm.mobile)) {
                    uni.showToast({
                        title: '请输入正确的手机号',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.accountRegisterForm.password) {
                    uni.showToast({
                        title: '请输入密码',
                        icon: 'none'
                    });
                    return false;
                }
                if (!/^[a-zA-Z0-9_]{6,20}$/.test(this.accountRegisterForm.password)) {
                    uni.showToast({
                        title: '密码必须是6-20位字母、数字或下划线',
                        icon: 'none'
                    });
                    return false;
                }
            }
            return true;
        },
        async handleLogin() {
            if (!this.validateLoginForm()) return;
            
            try {
                this.loading = true;
                const requestData = {
                    account: this.loginForm.account,
                    loginType: this.loginType,
                    password: this.loginType === 'password' ? this.loginForm.password : undefined,
                    code: this.loginType === 'code' ? this.loginForm.code : undefined
                };
                
                // 删除未定义的属性
                Object.keys(requestData).forEach(key => 
                    requestData[key] === undefined && delete requestData[key]
                );
                
                console.log('准备发送登录请求:', JSON.stringify(requestData));
                const response = await login(requestData);
                console.log('登录响应完整数据:', JSON.stringify(response));
                
                if (response && response.code === 200) {
                    // 用户信息直接在data中，而不是在data.userInfo中
                    const responseData = response.data;
                    console.log('登录成功, 用户信息:', JSON.stringify(responseData));
                    console.log('获取到的token:', responseData.token);
                    
                    // 确保token存储正确，不需要额外处理Bearer前缀
                    uni.setStorageSync('token', responseData.token);
                    // 存储整个用户信息对象
                    uni.setStorageSync('userInfo', responseData);
                    
                    const userType = responseData.userType;
                    const roles = responseData.roles || [];
                    
                    uni.showToast({
                        title: '登录成功',
                        icon: 'success',
                        duration: 1500
                    });
                    
                    setTimeout(() => {
                        if (userType === 'ADMIN' || roles.includes('ROLE_ADMIN')) {
                            console.log('检测到管理员账号, 提示前往管理端');
                            uni.showModal({
                                title: '管理员账号',
                                content: '检测到您使用的是管理员账号，请前往管理端登录。',
                                showCancel: false,
                                success: () => {
                                    uni.clearStorageSync();
                                    uni.reLaunch({
                                        url: '/pages/index/index'
                                    });
                                }
                            });
                        } else if (userType === 'SERVICE' || roles.includes('ROLE_CUSTOMER_SERVICE')) {
                            console.log('检测到客服账号, 跳转到客服控制台');
                            // 跳转前确认缓存
                            console.log('跳转前再次验证token:', uni.getStorageSync('token'));
                            console.log('跳转前再次验证用户信息:', JSON.stringify(uni.getStorageSync('userInfo')));
                            
                            uni.reLaunch({
                                url: '/pages/service/console'
                            });
                        } else {
                            console.log('普通用户, 跳转到聊天页面');
                            // 跳转前确认缓存
                            console.log('跳转前再次验证token:', uni.getStorageSync('token'));
                            console.log('跳转前再次验证用户信息:', JSON.stringify(uni.getStorageSync('userInfo')));
                            
                            uni.reLaunch({
                                url: '/pages/chat/chat'
                            });
                        }
                    }, 1500);
                } else {
                    throw new Error(response?.message || '登录失败');
                }
            } catch (error) {
                console.error('登录错误:', error);
                uni.showToast({
                    title: error.message || '登录失败，请检查账号密码',
                    icon: 'none',
                    duration: 2000
                });
            } finally {
                this.loading = false;
            }
        },
        async handleRegister() {
            if (!this.validateRegisterForm() || this.loading) return;
            
            this.loading = true;
            try {
                let response;
                
                if (this.registerType === 'email') {
                    // 邮箱验证码注册
                    const registerData = {
                        account: this.registerForm.account,
                        password: this.registerForm.password,
                        code: this.registerForm.code
                    };
                    console.log('准备发送邮箱验证码注册请求:', JSON.stringify(registerData));
                    response = await registerByCode(registerData);
                } else {
                    // 账号密码注册
                    const registerData = {
                        username: this.accountRegisterForm.username,
                        nickname: this.accountRegisterForm.nickname,
                        mobile: this.accountRegisterForm.mobile,
                        email: this.accountRegisterForm.email,
                        password: this.accountRegisterForm.password
                    };
                    console.log('准备发送账号密码注册请求:', JSON.stringify(registerData));
                    response = await registerByAccount(registerData);
                }
                
                console.log('注册响应完整数据:', JSON.stringify(response));
                
                uni.showToast({
                    title: '注册成功',
                    icon: 'success',
                    duration: 2000
                });
                
                // 重置表单
                if (this.registerType === 'email') {
                    this.registerForm = {
                        account: '',
                        password: '',
                        code: ''
                    };
                } else {
                    this.accountRegisterForm = {
                        username: '',
                        nickname: '',
                        mobile: '',
                        email: '',
                        password: ''
                    };
                }
                
                // 成功注册后自动切换到登录表单
                console.log('注册成功，准备切换到登录表单');
                setTimeout(() => {
                    this.switchToLogin();
                }, 1800);
                
            } catch (error) {
                console.error('注册失败:', error);
                uni.showToast({
                    title: error.message || '注册失败，请重试',
                    icon: 'none',
                    duration: 2000
                });
            } finally {
                this.loading = false;
            }
        },
        async handleGetCode() {
            if (!this.loginForm.account) {
                uni.showToast({
                    title: '请输入邮箱',
                    icon: 'none'
                });
                return;
            }
            
            if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.loginForm.account)) {
                uni.showToast({
                    title: '请输入正确的邮箱地址',
                    icon: 'none'
                });
                return;
            }
            
            try {
                this.loading = true;
                console.log('准备获取登录验证码，邮箱:', this.loginForm.account);
                
                await getLoginCode(this.loginForm.account);
                
                console.log('登录验证码获取成功，开始倒计时');
                this.countdown = 60;
                
                // 清除现有计时器
                if (this.timer) {
                    clearInterval(this.timer);
                }
                
                // 设置新的计时器
                this.timer = setInterval(() => {
                    if (this.countdown > 0) {
                        this.countdown--;
                    } else {
                        clearInterval(this.timer);
                        this.timer = null;
                    }
                }, 1000);
                
                uni.showToast({
                    title: '验证码已发送',
                    icon: 'success'
                });
            } catch (error) {
                console.error('获取验证码失败:', error);
                uni.showToast({
                    title: error.message || '获取验证码失败',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
            }
        },
        async sendRegisterCode() {
            if (!this.registerForm.account) {
                uni.showToast({
                    title: '请输入邮箱',
                    icon: 'none'
                });
                return;
            }
            
            if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.registerForm.account)) {
                uni.showToast({
                    title: '请输入正确的邮箱地址',
                    icon: 'none'
                });
                return;
            }
            
            try {
                this.loading = true;
                console.log('准备获取注册验证码，邮箱:', this.registerForm.account);
                
                await getRegisterCode(this.registerForm.account);
                
                console.log('注册验证码获取成功，开始倒计时');
                this.registerCodeTimer = 60;
                
                // 清除现有计时器
                if (this.registerTimer) {
                    clearInterval(this.registerTimer);
                }
                
                // 设置新的计时器
                this.registerTimer = setInterval(() => {
                    if (this.registerCodeTimer > 0) {
                        this.registerCodeTimer--;
                    } else {
                        clearInterval(this.registerTimer);
                        this.registerTimer = null;
                    }
                }, 1000);
                
                uni.showToast({
                    title: '验证码已发送',
                    icon: 'success'
                });
            } catch (error) {
                console.error('获取验证码失败:', error);
                uni.showToast({
                    title: error.message || '获取验证码失败',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
            }
        },
        switchToRegister() {
            this.isLogin = false;
            
            // 自动滚动到页面顶部
            setTimeout(() => {
                uni.pageScrollTo({
                    scrollTop: 0,
                    duration: 300
                });
            }, 300);
        },
        switchToLogin() {
            this.isLogin = true;
            
            // 自动滚动到页面顶部
            setTimeout(() => {
                uni.pageScrollTo({
                    scrollTop: 0,
                    duration: 300
                });
            }, 300);
        },
        closeResetPasswordModal() {
            this.showResetPasswordModal = false;
            this.resetPasswordStep = 1;
            this.resetPasswordForm = {
                email: '',
                code: '',
                newPassword: '',
                confirmPassword: ''
            };
        },
        async sendPasswordResetCode() {
            if (!this.resetPasswordForm.email) {
                uni.showToast({
                    title: '请输入邮箱',
                    icon: 'none'
                });
                return;
            }
            
            if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.resetPasswordForm.email)) {
                uni.showToast({
                    title: '请输入正确的邮箱地址',
                    icon: 'none'
                });
                return;
            }
            
            this.loading = true;
            try {
                console.log('准备获取重置密码验证码，邮箱:', this.resetPasswordForm.email);
                
                await getResetPasswordCode(this.resetPasswordForm.email);
                
                console.log('重置密码验证码获取成功');
                this.startResetPasswordCodeTimer();
                
                uni.showToast({
                    title: '验证码已发送',
                    icon: 'success'
                });
            } catch (error) {
                console.error('获取验证码失败:', error);
                uni.showToast({
                    title: error.message || '获取验证码失败，请重试',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
            }
        },
        startResetPasswordCodeTimer() {
            this.resetPasswordCodeTimer = 60;
            
            // 清除之前的计时器
            if (this.resetPasswordTimer) {
                clearInterval(this.resetPasswordTimer);
            }
            
            // 开始新的计时器
            this.resetPasswordTimer = setInterval(() => {
                if (this.resetPasswordCodeTimer > 0) {
                    this.resetPasswordCodeTimer--;
                } else {
                    clearInterval(this.resetPasswordTimer);
                    this.resetPasswordTimer = null;
                }
            }, 1000);
        },
        verifyResetCode() {
            if (!this.resetPasswordForm.email) {
                uni.showToast({
                    title: '请输入邮箱',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.resetPasswordForm.code) {
                uni.showToast({
                    title: '请输入验证码',
                    icon: 'none'
                });
                return;
            }
            
            this.resetPasswordStep = 2;
        },
        async handleResetPassword() {
            if (!this.resetPasswordForm.newPassword) {
                uni.showToast({
                    title: '请输入新密码',
                    icon: 'none'
                });
                return;
            }
            
            if (!/^[a-zA-Z0-9_]{6,20}$/.test(this.resetPasswordForm.newPassword)) {
                uni.showToast({
                    title: '密码必须是6-20位字母、数字或下划线',
                    icon: 'none'
                });
                return;
            }
            
            if (this.resetPasswordForm.newPassword !== this.resetPasswordForm.confirmPassword) {
                uni.showToast({
                    title: '两次输入的密码不一致',
                    icon: 'none'
                });
                return;
            }
            
            this.loading = true;
            try {
                await resetPassword({
                    email: this.resetPasswordForm.email,
                    code: this.resetPasswordForm.code,
                    newPassword: this.resetPasswordForm.newPassword
                });
                
                this.resetPasswordStep = 3;
            } catch (error) {
                console.error('重置密码失败:', error);
                uni.showToast({
                    title: error.message || '重置密码失败，请重试',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
            }
        },
        onUsernameInput() {
            if (this.accountRegisterForm.username) {
                this.generateRandomUsername(this.accountRegisterForm.username);
            } else {
                this.randomUsernameSuggestions = [];
            }
        },
        generateRandomUsername(inputText = '') {
            this.randomUsernameSuggestions = [];
            
            const prefix = inputText.trim() ? inputText.trim().charAt(0) : '';
            
            for (let i = 0; i < 5; i++) {
                const adj = this.adjectives[Math.floor(Math.random() * this.adjectives.length)];
                const noun = this.nouns[Math.floor(Math.random() * this.nouns.length)];
                const num = Math.floor(Math.random() * 100) + 1;
                
                if (prefix) {
                    this.randomUsernameSuggestions.push(`${prefix}${adj}${noun}x${num}`);
                } else {
                    this.randomUsernameSuggestions.push(`${adj}${noun}x${num}`);
                }
            }
        },
        hideUsernameSuggestions() {
            setTimeout(() => {
                this.showUsernameSuggestions = false;
            }, 200);
        },
        selectUsername(name) {
            this.accountRegisterForm.username = name;
            this.accountRegisterForm.nickname = name;
        },
        toggleForm() {
            this.isLogin = !this.isLogin;
        },
        checkMobileView() {
            this.isMobileView = window.innerWidth <= 570;
        }
    },
    mounted() {
        // 初始化随机用户名建议
        this.generateRandomUsername();
        
        // 添加移动设备检测
        this.checkMobileView();
        window.addEventListener('resize', this.checkMobileView);
    },
    beforeDestroy() {
        // 移除窗口大小变化监听
        window.removeEventListener('resize', this.checkMobileView);
        
        // 清除所有计时器
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
        
        if (this.registerTimer) {
            clearInterval(this.registerTimer);
            this.registerTimer = null;
        }
        
        if (this.resetPasswordTimer) {
            clearInterval(this.resetPasswordTimer);
            this.resetPasswordTimer = null;
        }
    },
}
</script>

<style lang="scss">
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700;800&display=swap');
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css');

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body, html {
    font-family: 'Poppins', sans-serif;
    min-height: 100vh;
    overflow-x: hidden;
}

.login-container {
    position: relative;
    width: 100%;
    min-height: 100vh;
    background-color: #fff;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
}

.back-btn {
    position: absolute;
    top: 20px;
    left: 20px;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #f5f6fa;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    z-index: 100;
    transition: background-color 0.3s;
}

.back-btn:hover {
    background-color: #e8eaf6;
}

.back-btn i {
    font-size: 18px;
    color: #5c6bc0;
}

.forms-container {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
}

.signin-signup {
    position: absolute;
    top: 50%;
    left: 75%;
    transform: translate(-50%, -50%);
    width: 50%;
    display: grid;
    grid-template-columns: 1fr;
    z-index: 5;
    transition: 1s 0.7s ease-in-out;
}

form {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    padding: 0 5rem;
    overflow-y: auto;
    min-height: 500px;
    max-height: 85vh;
    grid-column: 1 / 2;
    grid-row: 1 / 2;
    transition: 0.2s 0.7s ease-in-out;
    width: 100%;
}

form.sign-in-form {
    z-index: 2;
    opacity: 1;
    transition: 0.5s 0.7s ease-in-out;
}

form.sign-up-form {
    z-index: 1;
    opacity: 0;
    transition: 0.5s 0.7s ease-in-out;
    min-height: 600px;
}

.title {
    font-size: 2rem;
    color: #444;
    margin-bottom: 10px;
    text-align: center;
    width: 100%;
}

.input-field,
.login-type,
.register-type,
.btn.solid,
.forgot-password,
.register-form-content {
    max-width: 380px;
    width: 100%;
    margin-left: auto;
    margin-right: auto;
}

.input-field {
    max-width: 380px;
    width: 100%;
    height: 55px;
    background-color: #f0f0f0;
    margin: 10px 0;
    border-radius: 55px;
    display: flex;
    align-items: center;
    padding: 0 1rem;
    position: relative;
    transition: all 0.3s ease;
}

.input-field:focus-within {
    box-shadow: 0 0 0 2px rgba(92, 107, 192, 0.2);
    background-color: #fff;
}

.input-field i {
    text-align: center;
    color: #acacac;
    line-height: 55px;
    transition: 0.5s;
    font-size: 1.1rem;
    margin-right: 10px;
}

.input-field:focus-within i {
    color: #5c6bc0;
}

.input-field input {
    background: none;
    outline: none;
    border: none;
    line-height: 1;
    font-weight: 600;
    font-size: 1.1rem;
    color: #333;
    width: 100%;
}

.input-field input::placeholder {
    color: #aaa;
    font-weight: 500;
}

.verification-field {
    position: relative;
}

.code-btn {
    background: none;
    border: none;
    outline: none;
    color: #5c6bc0;
    font-weight: 600;
    cursor: pointer;
    padding: 8px 12px;
    border-radius: 20px;
    transition: background-color 0.3s;
    white-space: nowrap;
    position: absolute;
    right: 10px;
}

.code-btn:hover:not(:disabled) {
    background-color: #e8eaf6;
}

.code-btn:disabled {
    color: #ccc;
    cursor: not-allowed;
}

.btn {
    width: 150px;
    height: 49px;
    border: none;
    outline: none;
    border-radius: 48px;
    cursor: pointer;
    background-color: #5c6bc0;
    color: #fff;
    text-transform: uppercase;
    font-weight: 600;
    margin: 10px 0;
    transition: all 0.5s;
}

.btn:hover:not(:disabled) {
    background-color: #3f51b5;
    box-shadow: 0 4px 8px rgba(92, 107, 192, 0.3);
    transform: translateY(-2px);
}

.btn:active:not(:disabled) {
    transform: translateY(0);
    box-shadow: 0 2px 4px rgba(92, 107, 192, 0.3);
}

.btn:disabled {
    background-color: #c5cae9;
    cursor: not-allowed;
}

.btn.solid {
    width: 100%;
    max-width: 380px;
}

.btn.transparent {
    background: none;
    border: 2px solid #fff;
    width: 130px;
    height: 41px;
    font-weight: 600;
    font-size: 0.8rem;
}

.login-type, .register-type {
    display: flex;
    width: 100%;
    max-width: 380px;
    margin-bottom: 15px;
    margin-top: 5px;
    background-color: #f0f0f0;
    border-radius: 55px;
    overflow: hidden;
}

.login-type span, .register-type span {
    flex: 1;
    text-align: center;
    padding: 12px 0;
    cursor: pointer;
    transition: 0.5s;
    color: #999;
}

.login-type span.active, .register-type span.active {
    background-color: #5c6bc0;
    color: #fff;
    font-weight: 600;
}

.register-form-content {
    width: 100%;
    max-width: 380px;
    display: flex;
    flex-direction: column;
    align-items: center;
    max-height: 60vh;
    overflow-y: auto;
    padding-right: 10px;
    scrollbar-width: thin;
    scrollbar-color: #ccc #f1f1f1;
}

.register-form-content::-webkit-scrollbar {
    width: 5px;
}

.register-form-content::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

.register-form-content::-webkit-scrollbar-thumb {
    background: #ccc;
    border-radius: 10px;
}

.register-form-content::-webkit-scrollbar-thumb:hover {
    background: #999;
}

.input-field-wrapper {
    width: 100%;
    position: relative;
    margin-bottom: 20px;
}

.username-suggestions {
    position: absolute;
    width: 100%;
    max-height: 150px;
    overflow-y: auto;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    z-index: 100;
    margin-top: 5px;
    scrollbar-width: thin;
    scrollbar-color: #ccc #f1f1f1;
    transition: all 0.3s ease;
    border: 1px solid #e0e0e0;
}

.suggestion-title {
    font-size: 0.85rem;
    font-weight: 500;
    color: #777;
    padding: 8px 15px;
    border-bottom: 1px solid #eee;
    background-color: #f8f9fa;
}

.username-suggestions::-webkit-scrollbar {
    width: 5px;
}

.username-suggestions::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

.username-suggestions::-webkit-scrollbar-thumb {
    background: #ccc;
    border-radius: 10px;
}

.username-suggestion-item {
    padding: 10px 15px;
    cursor: pointer;
    transition: background-color 0.3s;
    font-size: 0.9rem;
    color: #555;
}

.username-suggestion-item:hover {
    background-color: #f5f6fa;
    color: #5c6bc0;
}

.forgot-password {
    margin: 15px 0;
    text-align: right;
    width: 100%;
    max-width: 380px;
}

.forgot-password span {
    color: #5c6bc0;
    cursor: pointer;
    font-size: 0.9rem;
    transition: 0.3s;
}

.forgot-password span:hover {
    text-decoration: underline;
    color: #3f51b5;
}

.loading-spinner {
    width: 20px;
    height: 20px;
    border: 3px solid rgba(92, 107, 192, 0.2);
    border-top: 3px solid #5c6bc0;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 10px auto;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.panels-container {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
}

.panel {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: center;
    text-align: center;
    z-index: 7;
    padding: 3rem 17% 2rem 12%;
}

.left-panel {
    pointer-events: all;
    padding: 3rem 17% 2rem 12%;
}

.right-panel {
    pointer-events: none;
    padding: 3rem 12% 2rem 17%;
}

.panel .content {
    color: #fff;
    transition: 0.9s 0.6s ease-in-out;
}

.panel h3 {
    font-weight: 600;
    line-height: 1;
    font-size: 1.5rem;
}

.panel p {
    font-size: 0.95rem;
    padding: 0.7rem 0;
}

.image {
    width: 100%;
    max-width: 500px;
    transition: 1.1s 0.4s ease-in-out;
}

.right-panel .content, .right-panel .image {
    transform: translateX(800px);
}

/* 模态窗口样式 */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
    backdrop-filter: blur(5px);
    animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

.modal-container {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100%;
    max-width: 450px;
    background-color: #fff;
    border-radius: 15px;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
    z-index: 1001;
    overflow: hidden;
    animation: slideIn 0.3s ease;
}

@keyframes slideIn {
    from { 
        transform: translate(-50%, -60%);
        opacity: 0; 
    }
    to { 
        transform: translate(-50%, -50%);
        opacity: 1; 
    }
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 25px;
    border-bottom: 1px solid #eee;
}

.modal-header h3 {
    font-size: 1.3rem;
    color: #333;
    margin: 0;
}

.close-btn {
    font-size: 1.8rem;
    color: #999;
    cursor: pointer;
    transition: color 0.3s;
}

.close-btn:hover {
    color: #333;
}

.modal-body {
    padding: 25px;
}

.reset-password-step {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.success-message {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
}

.success-message i {
    font-size: 3rem;
    color: #4CAF50;
    margin-bottom: 15px;
}

.success-message p {
    font-size: 1.2rem;
    color: #333;
}

/* ANIMATION */
.login-container:before {
    content: "";
    position: absolute;
    height: 2000px;
    width: 2000px;
    top: -10%;
    right: 48%;
    background-image: linear-gradient(-45deg, #5c6bc0 0%, #3f51b5 100%);
    transition: 1.8s ease-in-out;
    border-radius: 50%;
    z-index: 6;
    transform: translateY(-50%);
}

/* 桌面端动画 */
@media (min-width: 571px) {
    .login-container.sign-up-mode:before {
        transform: translate(100%, -50%);
        right: 52%;
    }

    .login-container.sign-up-mode .left-panel .image,
    .login-container.sign-up-mode .left-panel .content {
        transform: translateX(-800px);
    }

    .login-container.sign-up-mode .right-panel .content,
    .login-container.sign-up-mode .right-panel .image {
        transform: translateX(0);
    }

    .login-container.sign-up-mode .left-panel {
        pointer-events: none;
    }

    .login-container.sign-up-mode .right-panel {
        pointer-events: all;
    }

    .login-container.sign-up-mode .signin-signup {
        left: 25%;
    }

    .login-container.sign-up-mode form.sign-in-form {
        z-index: 1;
        opacity: 0;
        transition: opacity 0.5s ease;
    }

    .login-container.sign-up-mode form.sign-up-form {
        z-index: 2;
        opacity: 1;
        transition: opacity 0.5s ease;
    }
    }

/* 移动设备适配 */
@media (max-width: 570px) {
    .login-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: flex-start;
        padding-top: 120px; /* 留出足够空间显示顶部波浪 */
        padding-left: 15px;
        padding-right: 15px;
        overflow-y: auto;
        overflow-x: hidden; /* 防止水平滚动 */
        width: 100%;
        box-sizing: border-box;
    }
    
    .login-container:before {
        content: "";
        position: fixed; /* 固定位置 */
        height: 250px; /* 减小高度 */
        width: 150%; /* 确保足够宽 */
        top: 0;  /* 置于顶部 */
        left: 50%;
        background-image: linear-gradient(-45deg, #5c6bc0 0%, #3f51b5 100%);
        transform: translateX(-50%);
        border-radius: 0 0 50% 50%; /* 只在底部设置圆角 */
        z-index: 0;
    }
    
    /* 移动设备动画效果优化 */
    .login-container.sign-up-mode:before {
        transform: translateX(-50%); /* 仅保持水平居中，不做水平移动 */
    }
    
    .forms-container {
        width: 100%;
        max-width: 380px;
        margin: 0 auto;
        position: relative;
        z-index: 10;
        height: auto;
        min-height: 70vh;
        box-sizing: border-box;
        padding-bottom: 80px; /* 为底部切换按钮留出空间 */
    }
    
    .signin-signup {
        width: 100%;
        position: relative;
        display: flex;
        justify-content: center;
        margin: 0 auto;
        padding: 0;
        box-sizing: border-box;
        left: 0;  /* 确保不偏移 */
        top: 0;
        transform: none;
    }
    
    .login-container.sign-up-mode .signin-signup {
        left: 0;
        transform: none;
    }
    
    form {
        width: 100%;
        min-height: auto;
        max-height: none;
        padding: 20px;
        margin: 0;
        background-color: rgba(255, 255, 255, 0.98);
        border-radius: 15px;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        box-sizing: border-box;
    }
    
    form.sign-in-form, form.sign-up-form {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        transition: opacity 0.5s ease;
        opacity: 0;
        z-index: 1;
        pointer-events: none;
        box-sizing: border-box;
        transform: none;  /* 确保没有变换 */
    }
    
    .login-container.sign-up-mode form.sign-in-form {
        transform: none; /* 移除水平位移 */
        transition: opacity 0.5s ease;
    }
    
    .login-container.sign-up-mode form.sign-up-form {
        transform: none; /* 移除水平位移 */
        transition: opacity 0.5s ease;
    }
    
    .login-container:not(.sign-up-mode) form.sign-in-form {
        opacity: 1;
        z-index: 2;
        pointer-events: all;
    }
    
    .login-container.sign-up-mode form.sign-up-form {
        opacity: 1;
        z-index: 2;
        pointer-events: all;
    }
    
    /* 输入框和按钮样式调整 */
    .input-field {
        width: 100%;
        margin: 10px 0;
        box-sizing: border-box;
    }
    
    .btn.solid {
        width: 100%;
        margin: 15px 0;
        box-sizing: border-box;
    }
    
    .login-type, .register-type {
        width: 100%;
        margin: 10px 0 15px;
        box-sizing: border-box;
    }
    
    /* 隐藏动画面板 */
    .panels-container {
        display: none;
    }
    
    /* 移动端切换按钮 */
    .mobile-toggle {
        display: flex;
        position: fixed;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        z-index: 1000;
        background-color: #5c6bc0;
        color: white;
        padding: 10px 20px;
        border-radius: 30px;
        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        cursor: pointer;
        font-weight: 600;
        text-align: center;
    }
    
    /* 返回按钮样式调整 */
    .back-btn {
        position: fixed;
        top: 20px;
        left: 20px;
        z-index: 100;
    }
    
    /* 模态窗口样式调整 */
    .modal-container {
        width: 90%;
    }
}
</style> 